// pages/limitedccoursedetails/limitedccoursedetails.js
var request = require("../../utils/request.js");
var WxParse = require('../../wxParse/wxParse.js');
const app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    headerHeight: 0,
    allowScroll: true,
    detail: [],
    footerHeight: 0,
    currentIndex: 0,
    contentHeight: 0,
    seeTab: {
      0: 0,
      1: 0,
      2: 0
    },
    modalFlag: false,
    collect: false,
    courseList: [],
    evaluate: [],
    contentType: 0,
    buy: 0,
    playIndex: 0,
    playTime: 0,
    organization: null,
    organizationData:null,
    share: [{
      show: true,
      icon: "/assets/images/more/0.png",
      title: "分享",
      button: true,
      type: "share",
      istyle: ''
    },
    {
      show: true,
      icon: "/assets/images/more/1.png",
      title: "投诉",
      istyle: 'filter: grayscale(100%);'
    },
    {
      show: true,
      icon: "/assets/images/more/2.png",
      title: "留言",
      istyle: 'filter: grayscale(100%);'
    }, {
      show: false,
      icon: "/assets/images/more/3.png",
      title: "评价",
      istyle: 'filter: grayscale(100%);'
    }]
  },
  onLoad: function (options) {
    {
      this.init(options.id);
    }
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    // this.Initialization();
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  //打开投诉菜单
  openIcon: function (e) {
    var that = this;
    var index = parseInt(e.currentTarget.dataset.index);
    var share = this.data.share;

    if (share[index]['show']) {
      var url = '';
      switch (index) {
        case 0:
          console.log("分享");
          break;
        case 1:
          console.log("投诉");
          break;
        case 2:
          break;
        case 3:
          var CourseID = that.data.detail.ID;
          wx.navigateTo({
            url: 'evaluate/index?CourseID=' + CourseID,
          })
          break;
      }
    }
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  onPageScroll(e) {
    var that = this;
    var index = that.data.currentIndex;
    that.getHeight('.tab_item_' + that.data.currentIndex);
    var scrollTop = e.scrollTop - 40;
    var str = "seeTab." + index;
    if (scrollTop <= this.data.headerHeight) {
      this.setData({
        [str]: e.scrollTop,
        allowScroll: true
      })
    }
    else {
      this.setData({
        [str]: e.scrollTop,
        allowScroll: false
      })
    }
  },

  //点击事件
  setTab(e) {
    var that = this;
    var id = e.currentTarget.dataset.id;
    console.log(id);
    this.setData({
      'currentIndex': id
    });
    that.getHeight('.tab_item_' + id).then(
      function (res) {
        console.log(res)
        that.scrollTo();
      }
    );

  },

  swiperChange(e) {
    var that = this;
    var id = e.detail.current;
    that.setData({
      'currentIndex': id
    });
    that.getHeight('.tab_item_' + id).then(
      function (res) {
        console.log(res)
        that.scrollTo();
      }
    );
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
  //初始化操作
  init(id) {
    request.request("api/Course/AddCourseClickCount?id=" + id, {}, "post", 1);
    this.getDetail(id);

  },
  //获取课程详情
  getDetail(id) {
    var that = this;
    wx.showLoading();
    var customId = app.globalData.userInfo['ID'];
    request.request("api/Course/GetCourse?courseId=" + id + "&customerId=" + customId, {}, 'get', 1).then(function (res) {
      console.log(res)
      if (res.data.status == 1) {

        that.getSubCourse(id);
        that.getEvaluate(id);

        

        var data = res.data.data;

        that.getOrganization(data.OrganizationID);

        var pic = data['Pic'].split(',')

        for (var j in pic) {
          pic[j] = "http://qbonbon.qclub-online.com/_Document/Image/" + pic[j]

        }
        console.log(data);
        data['Pic'] = pic[0];
        data['slider'] = pic;

        var collect = false;
        if (res.data.data.HasFocus == 1) {
          collect = true;
        }

        var share = false;
        if (data['HasBuy'] == 1) {
          share = true;
        }

        that.setData({
          detail: data,
          contentType: data['ContentType'],
          collect: collect,
          buy: data['HasBuy'],
          "share[3].show": share
        })
        console.log("buy:" + that.data.buy);
        WxParse.wxParse('article', 'html', res.data.data.Content, that, 5);
        that.utils();
        wx.hideLoading();
      }
    });
  },
  getSubCourse: function (id) {
    // 听课列表
    var that = this;
    request.request("api/Course/GetCourseDetails?courseId=" + id, {}, "get", 1).then(function (res) {
      console.log(res.data.data.length);
      if (res.data.status == 1) {
        var data = res.data.data;
        var detail = that.data.detail;
        console.log(detail);
        var playIndex = 0;
        var playTime = detail['TimeLength'];
        for (var i in data) {
          console.log(detail['CourseDetail_History_ID'], data[i]['ID']);
          if (detail['CourseDetail_History_ID'] == data[i]['ID']) {
            playIndex = i;
          }

          data[i]['Img'] = "http://qbonbon.qclub-online.com/_Document/Image/" + data[i]['Img'];
          data[i]['Url'] = "http://qbonbon.qclub-online.com/_Document/Video/" + data[i]['Url'];
        }

        that.setData({
          courseList: data,
          playIndex: playIndex,
          playTime: playTime
        })
      }
    });
  },
  //获取机构
  getOrganization: function (id) {
    var that = this;
    request.request("api/Organization/GetDetail", { organizationId: id, customerId: app.globalData.userInfo['ID'] }).then(function (res) {
      var result = res.data;
      
      if (result.status == 1){
        
        if (result.data['Logo'] != null){
          result.data['Logo'] = "http://qbonbon.qclub-online.com/_Document/Image/" + result.data['Logo'];
        }

        

        console.log(result.data);
        result.data['id'] = id;
        that.setData({
          organization:{
            "id": id,
            "logo":result.data.Logo,
            "name": result.data.Name,
            "desc": result.data.Slogan,
            "focus": result.data.HasFocus
          },
          organizationData:result.data
        })
      }
    })
  },
  // 获取评论列表
  getEvaluate: function (id) {
    var that = this;
    request.request("api/Course/GetCourseComments", { courseId: id }).then(function (res) {
      if (res.data.status == 1) {

        var data = res.data.data;
        for (var i in data) {

          var StarLevel = {}

          var star = data[i].StarLevel;
          for (var j = 0; j < 5; j++) {
            if (j <= star) {
              StarLevel[j] = true;
            }
            else {
              StarLevel[j] = false;
            }
          }

          data[i]['pickers'] = StarLevel;

        }
        console.log(data);
        that.setData({
          evaluate: data
        })

      }
    })
  },
  utils() {
    var that = this;
    var query = wx.createSelectorQuery();
    query.select('.header').boundingClientRect()
    query.exec((res) => {
      var viewHeight = res[0].height; // 获取list高度
      console.log(viewHeight)
      that.setData({
        headerHeight: viewHeight
      })
    })

    var query = wx.createSelectorQuery();
    query.select('.footer').boundingClientRect()
    query.exec((res) => {
      var footerHeight = res[0].height; // 获取list高度
      console.log(footerHeight)
      that.setData({
        footerHeight: footerHeight
      })
    })
    that.getHeight('.tab_item_' + that.data.currentIndex);
  },
  getHeight(className) {
    //console.log(className)
    // swiper高度
    var that = this;
    return new Promise(resolve => {
      var query = wx.createSelectorQuery();
      query.select(className).boundingClientRect()
      query.exec((res) => {
        var contentHeight = res[0].height; // 获取list高度
        //console.log(contentHeight != that.data.contentHeight)
        if (contentHeight != that.data.contentHeight) {
          that.setData({
            contentHeight: contentHeight
          })
        }
        resolve(res);
      })
    });
  },
  scrollTo() {
    var that = this;
    var index = that.data.currentIndex;
    wx.pageScrollTo({
      scrollTop: that.data.seeTab[index],
      duration: 0
    })
  },

  // 关闭弹窗
  stopmove(e) {
    return false;
  },
  stopClose(e) {
    return false;
  },
  //关闭按钮
  closeBtn(e) {
    this.setData({
      modalFlag: false
    })
  },
  //打开弹窗
  openModal(e) {
    this.setData({
      modalFlag: true
    })
  },
  //立即收藏
  collect: function () {
    wx.showLoading({
      title: '加载中...',
    })
    var that = this;
    var collect = this.data.collect;
    var customId = app.globalData.userInfo.ID;
    var CourseID = this.data.detail.ID;
    request.request("/api/Course/ChangeCustomerCourseCollectionState", { CustomerID: customId, CourseID: CourseID }, 'post', 1).then(function (res) {
      console.log(res)
      if (res.data.status == 1) {
        collect = collect ? false : true;
        that.setData({
          collect: collect,
        })
        wx.hideLoading();
      }
    });
  },

  //comfirmOrder确认订单，立刻购买
  comfirmOrder: function (e) {

    var data = this.data.detail;
    wx.setStorageSync("course", data)

    wx.navigateTo({
      url: 'comfirmOrder',
    })
  },

  //打开视频播放器
  openMedia: function (e) {

  },

  //机构详情页
  openView: function (e) {

    var organizationData = this.data.organizationData;

    wx.setStorageSync("organizationData", organizationData);

    wx.navigateTo({
      url: '../course/mechanism/index',
    })
  },

  //follow关注按钮
  follow: function (e) {
    var that = this;
    var id = e.currentTarget.dataset.id;
    request.request("api/Organization/ChangeFocusState", { OrganizationId: id, CustomerId: app.globalData.userInfo['ID']}, 'post', 1).then(function (res) {
      if(res.data.status == 1){
        wx.showToast({
          title: '操作成功',
        }); 

        var focus = that.data.organization.focus == true ? false : true;

        that.setData({
          "organization.focus": focus,
          "organizationData.HasFocus": focus
        });

      }
    });
    return false;
  },

  //audition
  play: function (e) {
    var that = this;

    var audition = e.currentTarget.dataset.audition;

    console.log("e", e);

    var index = e.currentTarget.dataset.index;

    console.log("index", index);

    var courseID = that.data.detail.ID;
    console.log(courseID);
    var playIndex = that.data.playIndex;
    var playTime = that.data.playTime;
    console.log(index != undefined);
    if (index != undefined) {
      playIndex = index;
      playTime = 0;
    }

    console.log("playIndex:" + playIndex);
    console.log("playTime:" + playTime);



    if (audition == 1) {
      var playList = [{ "id": that.data.courseList[0]['ID'], "name": that.data.courseList[0]['Title'], "url": that.data.courseList[0]['Url'] }];
      var courseList = JSON.stringify(playList);
    }
    else {
      var playList = [];
      var courseList = that.data.courseList;
      for (var i in courseList) {
        var arr = { "id": that.data.courseList[i]['ID'], "name": courseList[i]['Title'], "url": courseList[i]['Url'] };
        playList.push(arr);
      }

      var courseList = JSON.stringify(playList);
      console.log(courseList);

    }

    var contentType = that.data.contentType;
    console.log(contentType);

    if (contentType == 2) {

      wx.setStorageSync("playList", courseList);
      wx.navigateTo({
        url: '../media/music?courseID=' + courseID + '&playIndex=' + playIndex + '&playTime=' + playTime,
      })

    }

    if (contentType == 3) {

      wx.setStorageSync("videoList", courseList);
      wx.navigateTo({
        url: '../media/video'
      })

    }
  }
})